var async = require("async")

module.exports = function(app) {
	return new DBRemote(app);
};

var DBRemote = function(app) {
	this.app = app
	DBRemote.app = app
    DBRemote.dbService = this.app.get("dbService")
    if(DBRemote.dbService && DBRemote.dbService.db){
    	DBRemote.db = DBRemote.dbService.db
    }
}
var local = {}
//获取战绩
DBRemote.prototype.getHistory = function(uid,cb) {
	DBRemote.dbService.db.lrange("game:UNO:history:"+uid,0,-1,function(err,data) {
		if(!err){
			cb(true,data)
		}else{
			console.log(err)
			cb(true,[])
		}
	})
}

//保存房间战绩
DBRemote.prototype.saveRoomHistory = function(roomInfo,cb) {
	roomInfo.time = (new Date()).getTime()
	for(var i in roomInfo.players){
		local.savePlayerHistory(roomInfo.players[i].uid,JSON.stringify(roomInfo))
	}
	//战绩传到后台
    var messageInfo = {
      messageType : "historyRecord",
      roomInfo : roomInfo,
      time : (new Date()).getTime()
    }
    DBRemote.dbService.writeMessage(JSON.stringify(messageInfo))
	cb()
}
local.savePlayerHistory = function(uid,history) {
	DBRemote.dbService.db.lpush("game:UNO:history:"+uid,history,function(err) {
		if(!err){
			DBRemote.dbService.db.ltrim("game:UNO:history:"+uid,0,10)
		}
	})
}
/**
 * [保存金币数据]
 * @Author   wfd
 * @DateTime 2018-06-12
 * @param    {[type]}   obj [{uid : uid,score : score}]
 * @param    {[type]}   win [description]
 * @param    {Function} cb  [description]
 * @return   {[type]}       [description]
 */
DBRemote.prototype.saveGoldData = function(obj,win,cb) {
	for(var i = 0;i < obj.length;i++){
		if(obj[i].uid > 10000){
			DBRemote.app.rpc.db.task.updateTask(null,obj[i].uid,"goldplay",1,null)
			DBRemote.dbService.incrbyPlayer(obj[i].uid,"allGame",1,function(){})
			if(obj[i].uid == win){
				local.savePlayerGoldWin(obj[i].uid)
			}else{
				DBRemote.dbService.setPlayer(obj[i].uid,"curWin",0,function(){})
			}
			local.savePlayerGoldScore(obj[i].uid,obj[i].score)
		}
	}
	cb()
}

local.savePlayerGoldWin = function(uid) {
	DBRemote.dbService.incrbyPlayer(uid,"allWin",1,function(){})
	DBRemote.app.rpc.db.task.updateTask(null,uid,"goldwin",1,null)
	DBRemote.dbService.incrbyPlayer(uid,"curWin",1,function(flag,curValue){
		if(flag){
			DBRemote.app.rpc.db.task.updateTask(null,uid,"goldstreak",curValue,null)
			DBRemote.dbService.getPlayer(uid,"maxWin",function(value) {
				if(value !== false){
					if(curValue > value){
						DBRemote.dbService.incrbyPlayer(uid,"maxWin",1,function(){})
					}
				}
			})
		}
	})
}
local.savePlayerGoldScore = function(uid,score) {
	DBRemote.dbService.getPlayer(uid,"maxScore",function(value) {
		if(value !== false){
			if(score > value){
				DBRemote.dbService.setPlayer(uid,"maxScore",score,function(){})
			}
		}
	})
}